<template>
	<view class="m-date-time" :style="{ backgroundColor: props.backgroundColor }" @click.stop>
		<template v-if="props.mode === 'module' && !isPickerVisible">

			<view class="header">
				<view class="title" :style="{ color: props.titleColor }">{{ props.initData.DateTitle || '选择时间' }}</view>
				<!-- 常用时间段 -->
				<u-radio-group v-model="usualRange.selected" @change="onUsualRangeChange">
					<view class="usual-list">
						<u-radio v-for="(item, idx) in usualRange.options" :key="item.value" :name="item.value"
							:label="item.label" :border="false" />
					</view>
				</u-radio-group>

			</view>

			<!-- 自定义区：开始/结束按钮和弹出选择器触发 -->
			<view class="custom-area">
				<view :class="['date-btn', activeBtn === 'start' ? 'active' : '']" @click="selectDateButton('start')">
					<text class="btn-label">开始</text>
					<text class="btn-value">{{ formattedStart }}</text>
				</view>

				<view :class="['date-btn', activeBtn === 'end' ? 'active' : '']" @click="selectDateButton('end')">
					<text class="btn-label">结束</text>
					<text class="btn-value">{{ formattedEnd }}</text>
				</view>

				<view class="x-ec" style="flex: 1;flex-wrap: wrap;">
					<button type="primary" style="width: 110rpx;font-size: 14px;padding: 2px 4px;margin-bottom: 4px;"
						@click="confirm">确定</button>
					<button type="default"
						style="width: 110rpx;font-size: 14px;padding: 2px 4px;border: 1px solid #e8e8e8;margin-left: 5rpx;background-color: #e8e8e8;margin-bottom: 4px;"
						@click="reset">重置</button>
				</view>
			</view>
		</template>

		<!-- Picker 弹层 -->
		<template v-if="isPickerVisible">
			<view class="picker-layer">
				<view class="picker-body">
					<picker-view :indicator-style="props.indicatorStyle" :style="pickerStyle" :value="pickerIndexes"
						@change="onPickerChange">
						<picker-view-column>
							<view v-for="(y, i) in years" :key="y" class="wheel-item x-c">{{ y }}</view>
						</picker-view-column>
						<picker-view-column>
							<view v-for="(m, i) in months" :key="m" class="wheel-item x-c">{{ m }}</view>
						</picker-view-column>
						<picker-view-column>
							<view v-for="(d, i) in days" :key="d" class="wheel-item x-c">{{ d }}</view>
						</picker-view-column>
					</picker-view>
				</view>

				<view class="picker-header x-bc">
					<u-button type="default" style="border: 1px solid #e8e8e8;" @click="closePicker">取消</u-button>
					<u-button type="primary" @click="onPickerConfirm">完成</u-button>
				</view>
			</view>

		</template>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, computed, onMounted } from 'vue'

	// Props & Emits types
	interface Props {
		mode ?: 'module' | 'picker'
		backgroundColor ?: string
		titleColor ?: string
		formmat ?: any;
		indicatorStyle ?: string
		initData : {
			DateTitle : string;
			SDate : string; // yyyy-mm-dd
			EDate : string; // yyyy-mm-d
			// 可以添加其他可能存在的属性，用?表示可选
			[key : string] : any; // 如果还有其他不确定的属性
		} | any;
	}


	const props = withDefaults(defineProps<Props>(), {
		mode: 'module',
		backgroundColor: '#ffffff',
		titleColor: '#333333',
		formmat: {
			SDate: "SDate",
			EDate: "EDate",
			pickerDate: "SDate"
		},
		indicatorStyle: 'height: 44px;line-height: 44px;font-size: 12px;',
		showConfirm: true,
		showReset: true
	})

	const emit = defineEmits<{
		(e : 'update', payload : { start : string; end : string }) : void
		(e : 'confirm', payload : { start : string; end : string }) : void
		(e : 'reset') : void  // 新增重置事件
		(e : 'cancel') : void  // picker状态下的取消按钮事件
	}>()

	// 保存初始值用于重置
	const initialState = ref({
		start: '',
		end: ''
	})

	// 常用区间配置
	const usualRange = reactive({
		selected: '',
		options: [
			{ label: '今天', value: 'today' },
			{ label: '昨天', value: 'yesterday' },
			{ label: '最近7天', value: 'last7' },
			{ label: '最近30天', value: 'last30' },
		],
	})

	const isPickerVisible = ref(false);
	isPickerVisible.value = props.mode == "picker";

	const activeBtn = ref<'start' | 'end'>('start')
	let selected = reactive<any>({})

	const years = ref<string[]>([])
	const months = ref<string[]>([])
	const days = ref<string[]>([])
	const pickerIndexes = ref<number[]>([0, 0, 0]);
	initPickerData()
	const initY = Number((selected.start || todayStr()).split('-')[0])
	const initM = Number((selected.start || todayStr()).split('-')[1])
	fillDays(initY, initM)

	if (props.mode == "picker") {

		Object.assign(selected, {
			start: props.initData,
			end: props.initData
		});
		// 获取当前选中的日期，如果没有则使用今天的日期
		let cur = selected.start
		const defaultDate = todayStr(); // 默认使用今天的日期
		const dateToUse = cur || defaultDate; // 如果没有设置日期，使用今天
		// 解析日期为年、月、日
		const [y, m, d] = dateToUse.split('-').map(Number);


		// 计算Picker的索引位置
		const yIdx = years.value.indexOf(String(y));
		const mIdx = months.value.indexOf(pad(m));

		// 填充对应年月的天数
		fillDays(y, m);

		// 确保日期索引有效
		const dIdx = days.value.indexOf(pad(d));

		// 设置Picker索引，确保索引有效
		pickerIndexes.value = [
			yIdx >= 0 ? yIdx : 0,
			mIdx >= 0 ? mIdx : 0,
			dIdx >= 0 ? dIdx : 0
		];
	} else {
		Object.assign(selected, {
			start: props.initData[props.formmat.SDate],
			end: props.initData[props.formmat.Edate]
		})
	}


	const formattedStart = computed(() => selected.start)
	const formattedEnd = computed(() => selected.end)


	if (props.mode == "picker") {
		initialState.value.start = props.initData;
		initialState.value.end = props.initData;
	} else {
		initialState.value.start = props.initData[props.formmat.SDate];
		initialState.value.end = props.initData[props.formmat.EDate];
	};

	const pickerStyle = computed(() => ({ height: '440rpx', zIndex: 99 }))

	function initPickerData(centerYear = new Date().getFullYear()) {
		const yStart = centerYear - 50
		const yEnd = centerYear + 10
		years.value = []
		for (let y = yStart; y <= yEnd; y++) years.value.push(String(y))
		months.value = []
		for (let m = 1; m <= 12; m++) months.value.push(pad(m))
	}

	function fillDays(year : number, month : number) {
		const dCount = new Date(year, month, 0).getDate()
		days.value = []
		for (let d = 1; d <= dCount; d++) days.value.push(pad(d))
	}

	function openPickerFor(btn : 'start' | 'end') {
		activeBtn.value = btn;

		// 获取当前选中的日期，如果没有则使用今天的日期
		let cur = btn === 'start' ? selected.start : selected.end;
		const defaultDate = todayStr(); // 默认使用今天的日期
		const dateToUse = cur || defaultDate; // 如果没有设置日期，使用今天

		// 解析日期为年、月、日
		const [y, m, d] = dateToUse.split('-').map(Number);

		// 计算Picker的索引位置
		const yIdx = years.value.indexOf(String(y));
		const mIdx = months.value.indexOf(pad(m));

		// 填充对应年月的天数
		fillDays(y, m);

		// 确保日期索引有效
		const dIdx = days.value.indexOf(pad(d));

		// 设置Picker索引，确保索引有效
		pickerIndexes.value = [
			yIdx >= 0 ? yIdx : 0,
			mIdx >= 0 ? mIdx : 0,
			dIdx >= 0 ? dIdx : 0
		];

		// 显示Picker
		isPickerVisible.value = true;
	}

	function closePicker() {
		if (props.mode == "picker") {
			emit("cancel");
		} else {
			isPickerVisible.value = false
		}
	}

	function selectDateButton(btn : 'start' | 'end') {
		openPickerFor(btn)
	}

	function onPickerChange(e : any) {
		const idxs : number[] = e?.detail?.value ?? pickerIndexes.value
		pickerIndexes.value = idxs
		const y = Number(years.value[idxs[0]] || years.value[0])
		const m = Number(months.value[idxs[1]] || months.value[0])
		fillDays(y, m)
		if (idxs[2] >= days.value.length) idxs[2] = days.value.length - 1
	}

	function onPickerConfirm() {
		const [yIdx, mIdx, dIdx] = pickerIndexes.value
		const y = years.value[yIdx] ?? years.value[0]
		const m = months.value[mIdx] ?? months.value[0]
		const d = days.value[dIdx] ?? days.value[0]
		const dateStr = `${y}-${m}-${d}`

		if (props.mode == "picker") {

			emit('update', { start: selected.start, end: selected.end })
			emit('confirm', { start: dateStr, end: dateStr })
		} else {
			if (activeBtn.value === 'start') selected.start = dateStr
			else selected.end = dateStr
			usualRange.selected = ""
			isPickerVisible.value = false
		}
	}

	function confirm() {
		if (new Date(selected.start) > new Date(selected.end)) {
			const tmp = selected.start
			selected.start = selected.end
			selected.end = tmp
		}
		emit('update', { start: selected.start, end: selected.end })
		emit('confirm', { start: selected.start, end: selected.end })
	}

	// 重置方法实现
	function reset() {
		// 恢复初始日期
		selected.start = initialState.value.start
		selected.end = initialState.value.end

		// 重置常用区间选择
		usualRange.selected = ''

		// 关闭可能打开的选择器
		isPickerVisible.value = false

		// 触发重置事件，通知父组件
		emit('update', {
			start: selected.start,
			end: selected.end
		})
		emit('reset')
	}

	function onUsualRangeChange(val : any) {
		usualRange.selected = val
		const today = new Date()
		let s = todayStr()
		let e = todayStr()
		if (val === 'yesterday') {
			const t = addDays(today, -1)
			s = formatDate(t)
			e = s
		} else if (val === 'last7') {
			s = formatDate(addDays(today, -6))
			e = formatDate(today)
		} else if (val === 'last30') {
			s = formatDate(addDays(today, -29))
			e = formatDate(today)
		}
		selected.start = s
		selected.end = e
		emit('update', { start: selected.start, end: selected.end })
	}

	function pad(n : number) {
		return n < 10 ? `0${n}` : String(n)
	}

	function todayStr() {
		return formatDate(new Date())
	}

	function formatDate(d : Date) {
		return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
	}

	function addDays(d : Date, offset : number) {
		const t = new Date(d.getTime())
		t.setDate(t.getDate() + offset)
		return t
	}
</script>

<style lang="scss">
	.m-date-time {
		padding: 24rpx;
		height: 100%;
		position: relative;
	}

	.header {
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 32rpx;
		margin-bottom: 16rpx;
	}

	.usual-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}

	.custom-area {
		width: 100%;
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.date-btn {
		padding: 16rpx 24rpx;
		border-radius: 12rpx;
		border: 1px solid #e5e5e5;
	}

	.date-btn.active {
		border-color: #09bb07;
	}

	.btn-label {
		display: block;
		font-size: 24rpx;
	}

	.btn-value {
		display: block;
		font-size: 28rpx;
		margin-top: 8rpx;
	}

	.picker-layer {
		/* position: fixed;
		left: 0;
		right: 0;
		top: 0; */
		/* bottom: 0; */
		background: #fff;
		border-top-left-radius: 8px;
		border-top-right-radius: 8px;
		box-shadow: 0 -6px 12px rgba(0, 0, 0, 0.08);
		height: 100%;
	}

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 28rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.picker-title {
		font-size: 24rpx;
	}

	.picker-body {
		padding: 12rpx 0 36rpx 0;
	}

	.wheel-item {
		// height: 88rpx;
		// line-height: 88rpx;
		text-align: center;
	}
</style>